package com.jianduyuan.anhuixiaoneng.channel;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.google.gson.Gson;
//import com.umeng.message.PushAgent;
import com.jianduyuan.anhuixiaoneng.utils.DataCleanManager;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import io.flutter.Log;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

/**
 * @Description: Flutter 通信 交互
 * @Author: 下雨了
 * @CreateDate: 2021-10-22 14:13
 * @UpdateUser: 更新者
 * @UpdateDate: 2021-10-22 14:13
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class FlutterMethodChannel implements MethodChannel.MethodCallHandler {
    public static final String TAG = "FlutterMethodChannel";
    private static FlutterMethodChannel instance;

    private MethodChannel mChannel;

    private Context mContext;

    public static synchronized FlutterMethodChannel getInstance() {
        if (instance == null) {
            instance = new FlutterMethodChannel();
        }
        return instance;
    }

    public void registerWith(Context context, BinaryMessenger registrar) {
        mContext = context;
        mChannel = new MethodChannel(registrar, FlutterChannelConstant.METHOD_CHANNEL_NAME);
        mChannel.setMethodCallHandler(this);
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {

        try {
            if (methodCall(call, result)) {
                result.notImplemented();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "Exception:" + e.getMessage());
        }
    }

    private boolean methodCall(MethodCall call, MethodChannel.Result result) {
        if (FlutterChannelConstant.GET_CACHE_DATA.equals(call.method)) {
            getCacheData(result);
            return true;
        }
        if (FlutterChannelConstant.SET_MUTE_DURATION_SECONDS.equals(call.method)) {
            setMuteDurationSeconds(call, result);
            return true;
        }
        if (FlutterChannelConstant.SET_DISPLAY_NOTIFICATION_NUMBER.equals(call.method)) {
            setDisplayNotificationNumber(call, result);
            return true;
        }
        if (FlutterChannelConstant.IS_ENABLED.equals(call.method)) {
            isEnabled(call, result);
            return true;
        }
        if (FlutterChannelConstant.OPEN_LOCATION_SERVICE_SETTING.equals(call.method)) {
            openLocationServiceSetting(result);
            return true;
        }
        if (FlutterChannelConstant.OPEN_NOTIFICATION_SETTINGS.equals(call.method)) {
            openNotificationSettings(result);
            return true;
        }
        if (FlutterChannelConstant.INSTALL_APK.equals(call.method)) {
            installApk(call, result);
            return true;
        }
        return false;
    }

    /**
     * 判断当前友盟 推送的 当前状态
     * 通过mPushAgent.isEnabled() 来查询状态。 状态表示有没有启用/关闭推送功能， 不表示推送后台服务的运行状态。
     *
     * mPushAgent.isEnabled() 此方法已被取消
     */
    @Deprecated
    private void isEnabled(MethodCall call, MethodChannel.Result result) {
        String secodes = getParam(call, result, "content");
//        boolean enabled = PushAgent.getInstance(mContext).isEnabled();
        Map<String, Object> map = new HashMap<>();
        map.put("code", FlutterChannelConstant.METHOD_CHANNEL_CODE);
        map.put("message", "消息推送的当前状态");
        map.put("content", false);
        result.success(new Gson().toJson(map));
    }

    /**
     * 设置显示通知冷却时间 默认情况下，统一设备在1分钟内收到同一个应用的多条通知时，不会重复提醒
     */
    @Deprecated
    private void setMuteDurationSeconds(MethodCall call, MethodChannel.Result result) {
        int secodes = getParam(call, result, "content");
//        PushAgent.getInstance(mContext).setMuteDurationSeconds(secodes);
        Map<String, Object> map = new HashMap<>();
        map.put("code", FlutterChannelConstant.METHOD_CHANNEL_CODE);
        map.put("message", "设置显示通知冷却时间");
        map.put("content", true);
        result.success(new Gson().toJson(map));
    }

    /**
     * 友盟 设置显示通知的数量  参数为0 表示不限制个数
     */
    @Deprecated
    private void setDisplayNotificationNumber(MethodCall call, MethodChannel.Result result) {
        int content = getParam(call, result, "content");
//        PushAgent.getInstance(mContext).setDisplayNotificationNumber(content);
        Map<String, Object> map = new HashMap<>();
        map.put("code", FlutterChannelConstant.METHOD_CHANNEL_CODE);
        map.put("message", "设置显示通知的数量");
        map.put("content", true);
        result.success(new Gson().toJson(map));
    }

    /**
     * 获取缓存大小
     *
     * @param result
     */
    @Deprecated
    private void getCacheData(MethodChannel.Result result) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", FlutterChannelConstant.METHOD_CHANNEL_CODE);
        map.put("message", "获取缓存大小");

        String size;
        try {
            size = DataCleanManager.getInstance().getTotalCacheSize(mContext);
            Toast.makeText(mContext, size, Toast.LENGTH_LONG).show();
            map.put("content", size);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("content", "error");
            Toast.makeText(mContext, "error", Toast.LENGTH_LONG).show();

        }
//        executeOnMain(result, new Gson().toJson(map));
        result.success(new Gson().toJson(map));

    }

    /**
     * 打开定位服务设置
     * @param result
     */
    private void openLocationServiceSetting(MethodChannel.Result result) {
        Intent locationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        mContext.startActivity(locationIntent);
        result.success(true);
    }

    /**
     * openNotificationSettings
     */
    private void openNotificationSettings(MethodChannel.Result result) {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 26) {
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("android.provider.extra.APP_PACKAGE", mContext.getPackageName());
        } else if (Build.VERSION.SDK_INT >= 21) {
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", mContext.getPackageName());
            intent.putExtra("app_uid", mContext.getApplicationInfo().uid);
        } else {
            // 其他
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", mContext.getPackageName(), null));
        }

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
        result.success(true);
    }

    /**
     * 安装apk文件
     */
    private void installApk(MethodCall call, MethodChannel.Result result) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", FlutterChannelConstant.METHOD_CHANNEL_CODE);
        map.put("message", "安装apk文件");

        String path = getParam(call, result, "content");
        File file =  new File(path);
        if (!file.exists()) {
            map.put("content", false);
            result.success(new Gson().toJson(map));
            return;
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //7.0及以上
            Uri contentUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() +".fileProvider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        } else {
            //7.0以下
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
        }
        map.put("content", true);
        result.success(new Gson().toJson(map));
    }


    private final Handler mHandler = new Handler(Looper.getMainLooper());

    private void executeOnMain(MethodChannel.Result result, Object param) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            try {
                result.success(param);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    result.success(param);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static <T> T getParam(MethodCall methodCall, MethodChannel.Result result, String param) {
        T value = methodCall.argument(param);
        if (value == null) {
            result.error("missing param", "cannot find param:" + param, 1);
        }
        return value;
    }
}
